$(function(){
     
     if(!detectmob()){
         console.log('PC端页面');
         pcLoad();
     }
     else{
         console.log('手机端页面');
         mobileLoad();
     }

     
})

function pcLoad(){

     lazyLoadImg();
     lazyAnimation();
     
     var clock;

     $(window).on('scroll',function () {

          lazyLoadImg();
          lazyAnimation();

          if (clock) { // 如果在300毫秒内进行scroll的话，都会被clearTimeout掉，setTimeout不会执行。
                    //如果有300毫秒外的操作，会得到一个新的timeID即clock，会执行一次setTimeout,然后保存这次setTimeout的ID，
                      //对于300毫秒内的scroll事件，不会生成新的timeID值，所以会一直被clearTimeout掉，不会执行setTimeout.
               clearTimeout(clock);
           }

           clock = setTimeout(function () {
               lazyLoadImg();
               lazyAnimation();
           },300)
     });

}

function mobileLoad(){

     lazyMobileImg();

     var clock;

     $(window).on('scroll',function () {

          lazyMobileImg();

          if (clock) {
               clearTimeout(clock);
          }

          clock = setTimeout(function () {
              lazyMobileImg();
           },300)

     });

}

function checkshow($el, offset){
    
	var scrollTop = $(window).scrollTop();
	var windowHeight = $(window).height();
	var offsetTop = $el.offset().top;

	if (offsetTop < (scrollTop + windowHeight + offset) && offsetTop >= scrollTop) { //在2个临界状态之间的就为出现在视野中的
            return true;
    }

    return false;
}

function contentShow($el){

	$el.closest('.container').addClass('animate-active');

}

function imgShow($el){

    $el.css('background-image','url('+$el.attr('data-src')+')');

    $el.addClass('done');

}

function mobileImgShow($el){

     $el.attr('src', $el.attr('data-src'));

     $el.addClass('done');

}

function hadShow($el){

	return $el.closest('.container').hasClass('animate-active');
}

function imgHadShow($el){

    return $el.hasClass('done');

}


function lazyAnimation(){

	$('.flag').each(function(index, el) {
		
          if(checkshow($(this),0) && !hadShow($(this))){

          	   contentShow($(this));

          }

	});
}

function lazyLoadImg(){

    $('section').each(function(index, el) {
    	  
          if(checkshow($(this),200) && !imgHadShow($(this)))
          {
          	   imgShow($(this));
          }

    });

}

function lazyMobileImg(){

     $('section >img').each(function(index, el) {
           
           if(checkshow($(this),0) && !imgHadShow($(this))){

                mobileImgShow($(this));

           }

     });

}

function detectmob() {  
      if( navigator.userAgent.match(/Android/i)  
      || navigator.userAgent.match(/webOS/i)  
      || navigator.userAgent.match(/iPhone/i)  
      || navigator.userAgent.match(/iPad/i)  
      || navigator.userAgent.match(/iPod/i)  
      || navigator.userAgent.match(/BlackBerry/i)  
      || navigator.userAgent.match(/Windows Phone/i)  
      ){  
          return true;  
      }  
      else {  
          return false;  
      }  
}  